﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Warehouse.Web.AppCode;

namespace Warehouse.Web
{
    public partial class Login : BasePage
    {
        private readonly int FailedPasswordAttemptWindowMinutes = 3;
        protected void Page_Load(object sender, EventArgs e)
        {
            this.ltMessage.Text = string.Empty;
            if (!IsPostBack)
            {
                if (string.Compare(Request.QueryString["type"], "logout", true) == 0)
                {
                    this.txtUserName.Text = string.Empty;
                    this.txtPassword.Text = string.Empty;
                    CustomAuthentication.SignOut();
                    Session.RemoveAll();
                    Response.Redirect(CustomAuthentication.DefaultUrl, true);
                }
            }
        }

        protected void btnLogin_OnClick(object sender, EventArgs e)
        {
            string username = this.txtUserName.Text.Trim();
            string password = this.txtPassword.Text;

            bool valid = true;
            if (string.IsNullOrEmpty(username))
            {
                this.txtUserNameRequiredFieldValidator.IsValid = false;
                valid = false;
            }
            if (string.IsNullOrEmpty(password))
            {
                this.txtPasswordRequiredFieldValidator.IsValid = false;
                valid = false;
            }
            if (valid)
            {
                bool reachFailedPasswordAttemptMaxCount;

                int userId = 0;
                if (CustomAuthentication.Authenticate(username, password, out reachFailedPasswordAttemptMaxCount,out userId))
                {
                    this.Page.Session["UserPermission"] = Warehouse.DataAccess.PermissionInUser.GetPermissionsByUser(userId);
                    if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                    {
                        Response.Redirect(Request.QueryString["ReturnUrl"]);
                    }
                    else
                    {
                        Response.Redirect(CustomAuthentication.DefaultUrl);
                    }
                }
                else if (reachFailedPasswordAttemptMaxCount)
                {
                    this.ltMessage.Text = string.Format("尝试错误密码次数过多，{0}分钟后自动解锁", FailedPasswordAttemptWindowMinutes);
                }
                else
                {
                    this.ltMessage.Text = "用户名或密码错误";
                }
            }
        }
    }
}
